package com.example.user2.controller;

import com.example.user2.service.impl.LoginService;
import com.example.user2.entity.User;
import com.example.user2.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Slf4j
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    //打开主页
    @RequestMapping(value = {"/index","/main"})
    public String index(){
        log.info("打开主页");
        return "forward:index.html";
    }
    //打开登陆界面
    @RequestMapping(value = "/login")
    public String login(){
        log.info("打开登陆界面");
        return "login.html";
    }

    //登陆验证
    @Autowired
    private LoginService loginService;
    @RequestMapping(value = "/userlogin",params = {"username","password"},name = "登陆验证")
//    @ResponseBody
    public String userlogin(User user){
        log.info(":"+user);
        if (loginService.login(user.getUsername(), user.getPassword())){
            return "loginsuccess.html";
        }else {
            return "forward:login.html";
        }
    }
    //处理访问登陆页面的请求
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public ModelAndView showregister(ModelAndView modelAndView){
        //设置访问的界面
        modelAndView.setViewName("register");
        //设置数据
        modelAndView.addObject("user", new User());
        return modelAndView;
    }

    //处理注册数据
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public ModelAndView handleregister(ModelAndView modelAndView,User user){
        try {
            userService.register(user);
            modelAndView.addObject("success","注册成功");
        } catch (Exception e) {
            modelAndView.addObject("error","注册失败");
            log.error(e.getMessage());
        }
        return modelAndView;
    }

}